package org.wevil.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Druid配置
 */
@Configuration
public class DruidConfig {

    /**
     * 绑定配置的bean
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置访问druid监控
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        // 配置后台监控页面地址
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(
                new StatViewServlet(),
                "/druid/*"
        );
        Map<String, String> map = new HashMap<>();
        // 后台登陆的用户名和密码
        // 用户名密码可以放到数据库
        map.put("loginUsername", "admin"); // 用户名
        map.put("loginPassword", "123456"); // 密码
        // 访问权限
        //map.put("allow", "localhost"); //只允许本机访问
        map.put("allow",""); //所有人都可以访问
        // 拒绝访问
        //map.put("deny", "192.168.1.1"); //ip会被拒绝访问
        bean.setInitParameters(map);
        return bean;
    }

    /**
     * 过滤不需要监控的后缀
     * */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //配置内容
        // 配置哪些请求可以被过滤
        Map<String, String> map = new HashMap<>();
        map.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        bean.setInitParameters(map);
        bean.setUrlPatterns(Collections.singletonList("/*"));
        return bean;
    }
}
